/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.eschool.dao;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.eschool.model.Alert;
import com.eschool.model.Permission;
import com.eschool.util.HibernateUtil;
import com.eschool.util.JdbcUtil;

/**
 *
 * @author Ammar
 */
public class PermissionDao {

    
    public static boolean setPermission(Permission permission) {
    	
    	boolean isInserted = false;
    	
    	Connection connection = JdbcUtil.openConnection();
		
		try{
			CallableStatement storedProc = connection.prepareCall("{ call InsertPerm(?,?,?,?,?) }");
			
			storedProc.setInt(1, permission.getParentId());
			storedProc.setString(2, permission.getTitle());
			storedProc.setString(3, permission.getUrl());
			storedProc.setString(4, permission.getUrl());
			storedProc.setString(5, permission.getDescription());
			
			storedProc.execute();
		
			isInserted = true;
			
			connection.close();
		}
		
		catch(Exception e){
			isInserted = false;
			connection.close();
			e.printStackTrace();
		}
		finally{
			return isInserted;
		}
    }

	
	public static Permission getPermissionByProperty(String property, Object value) {
		
		Session session = HibernateUtil.currentSession();
	      
		Criteria crit = session.createCriteria(Permission.class);
		crit.add(Restrictions.eq(property, value));
		
		Permission permission = (Permission) crit.uniqueResult();

        HibernateUtil.closeSession(session);

        return permission;
	}

	
	public static List getPermissions(Map<String , Object> conditions) {
		
		Session session = HibernateUtil.currentSession();
		Criteria crit = session.createCriteria(Permission.class);
		
		if (conditions != null)
			
			for (Iterator iterator = conditions.entrySet().iterator(); iterator.hasNext();) {
			
				Map.Entry condition = (Map.Entry) iterator.next();
				
				crit.add(Restrictions.eq(((String) condition.getKey()), condition.getValue()));
			}
		
		List permissions = (List<Permission>) crit.list();
		
        HibernateUtil.closeSession(session);
        
        if(permissions == null)
        	return Collections.EMPTY_LIST;

        return permissions;
	}
	
	public static List<Permission> getAllPermissions() {
		Session session = HibernateUtil.currentSession();
	      
		Criteria crit = session.createCriteria(Permission.class);
		
		List permissions = crit.list();
		/*for (Iterator iterator = permissions.iterator(); iterator.hasNext();) {
			Permission permission = (Permission) iterator.next();
			*/

		
        HibernateUtil.closeSession(session);
        return permissions;
	}
}
